package com.zzyl.web.chatApi.service;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzyl.web.chatApi.dto.ChatRequest;
import com.zzyl.web.chatApi.dto.ChatResponse;
import com.zzyl.web.chatApi.exception.ApiException;
import lombok.RequiredArgsConstructor;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@RequiredArgsConstructor
public class DeepSeekService {
    private final OkHttpClient okHttpClient;
    private final Headers deepseekHeaders;
    @Value("${deepseek.api.url}")
    private String apiUrl;

    public ChatResponse chatCompletion(ChatRequest request) throws IOException, ApiException {
        ObjectMapper mapper = new ObjectMapper();
        String jsonBody = mapper.writeValueAsString(request);

        Request httpRequest = new Request.Builder()
                .url(apiUrl)
                .headers(deepseekHeaders)
                .post(RequestBody.create(MediaType.get("application/json"), jsonBody))
                .build();

        try (Response response = okHttpClient.newCall(httpRequest).execute()) {
            if (!response.isSuccessful()) {
                throw new ApiException("API请求失败: " + response.code());
            }
            return mapper.readValue(response.body().string(), ChatResponse.class);
        }
    }
}
